package com.xc.file.web.rest;

import com.xc.core.dto.TokenDto;
import com.xc.core.dto.UserAuthorityDto;
import com.xc.core.enums.RedisPrefix;
import com.xc.core.exception.OperateException;
import com.xc.core.exception.ResultException;
import com.xc.core.model.TokenModel;
import com.xc.core.utils.RedisUtils;
import com.xc.file.config.Constants;
import com.xc.file.entity.UserInfoEntity;
import com.xc.file.service.UserInfoService;
import com.xc.tool.http.HttpResult;
import com.xc.tool.utils.HttpUtils;
import com.xc.tool.utils.JSONUtils;
import com.xc.tool.utils.ObjectUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;


/**
 * <p>授权接口</p>
 *
 * @author xc
 * @version v1.0.0
 */
@Api(tags = {"授权接口"})
@RestController
public class AuthorizeRest {

    @Autowired
    private Constants constants;
    @Autowired
    private UserInfoService userInfoService;

    @GetMapping("/token")
    public Map getToken(@RequestParam String code) {
        // 获取token
        String url = constants.getTokenUrl() + "?appId=" + constants.getAppId() +
                "&appSecret=" + constants.getAppSecret() + "&code=" + code;
        HttpResult<TokenDto> httpResult = HttpUtils.get(url, TokenDto.class);
        if (httpResult.getCode() != 200) {
            ResultException resultException = JSONUtils.getObjectByString(httpResult.getMessage(), ResultException.class);
            throw new OperateException(resultException.getCode(), resultException.getMessage());
        }
        String token = httpResult.getData().getAccessToken();

        // 获取token全部信息
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        HttpResult<UserAuthorityDto> tokenHttpResult = HttpUtils.get(constants.getCurrentUserAuthorityUrl(), UserAuthorityDto.class, map);
        if (tokenHttpResult.getCode() != 200) {
            ResultException resultException = JSONUtils.getObjectByString(tokenHttpResult.getMessage(), ResultException.class);
            throw new OperateException(resultException.getCode(), resultException.getMessage());
        } else {
            TokenModel tokenModel = ObjectUtils.convert(new TokenModel(), httpResult.getData());
            tokenModel.setUserId(tokenHttpResult.getData().getUserId());
            tokenModel.setAuthorityCodes(tokenHttpResult.getData().getAuthorityCodes());
            // 创建本地用户信息
            UserInfoEntity userInfoEntity = userInfoService.getUserInfoByUserId(tokenModel.getUserId());
            if (userInfoEntity == null) {
                userInfoService.createUserInfo(tokenModel.getUserId(), tokenModel.getAccount());
            }
            RedisUtils.set(RedisPrefix.ACCESS.getKey() + token, JSONUtils.getStringByObject(tokenModel));
        }
        // 返回数据
        Map<String, Object> map1 = new HashMap<>();
        map1.put("accessToken", httpResult.getData().getAccessToken());
        map1.put("refreshToken", httpResult.getData().getRefreshToken());
        map1.put("validTime", httpResult.getData().getValidTime());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formatStr = formatter.format(httpResult.getData().getUpdateTime());
        map1.put("updateTime", formatStr);
        map1.put("authorityCodes", tokenHttpResult.getData().getAuthorityCodes());
        return map1;
    }

}
